package com.longmao.educenter.controller;

import com.google.gson.Gson;
import com.longmao.commonutils.JwtUtils;
import com.longmao.educenter.entity.UcenterMember;
import com.longmao.educenter.service.UcenterMemberService;
import com.longmao.educenter.utils.HttpClientUtil;
import com.longmao.educenter.utils.WxPropertiesUtils;
import com.longmao.servicebase.handler.LongMaoException;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.util.HashMap;

/**
 * @author longmao
 * @date 2022/2/22 11:30
 * Content:
 */
@Api(description="微信扫描二维码")
//@CrossOrigin //跨域
@Controller
@RequestMapping("/api/ucenter/wx")
public class WxApiController {

    @Autowired
    private UcenterMemberService memberService;

    /**
     * 用户微信登录,生成微信扫描二维码
     * @param session
     * @return
     */
    @GetMapping("/wxlogin")
    public String getWxCode(HttpSession session) {

        // 微信开放平台授权baseUrl
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        // 回调地址
        String redirectUrl = WxPropertiesUtils.WX_OPEN_REDIRECT_URL; //获取业务服务器重定向地址
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "UTF-8"); //url编码
        } catch (Exception e) {
            throw new LongMaoException(20001, e.getMessage());
        }

        // 防止csrf攻击（跨站请求伪造攻击）
        //String state = UUID.randomUUID().toString().replaceAll("-", "");//一般情况下会使用一个随机数
        String state = "longmao";//为了让大家能够使用我搭建的外网的微信回调跳转服务器，这里填写你在ngrok的前置域名

        // 采用redis等进行缓存state 使用sessionId为key 30分钟后过期，可配置
        //键："wechar-open-state-" + httpServletRequest.getSession().getId()
        //值：satte
        //过期时间：30分钟

        //生成qrcodeUrl
        String qrcodeUrl = String.format(
                baseUrl,
                WxPropertiesUtils.WX_OPEN_APP_ID,
                redirectUrl,
                state);

        return "redirect:" + qrcodeUrl; //redirect:重定向到请求的地址中
    }

    /**
     * 获取扫描人的信息
     * @param code
     * @param state
     * @param session
     * @return
     */
    @GetMapping("callback")
    public String callback(String code, String state, HttpSession session) {

        try {
            //得到授权临时票据code
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token"
                    + "?appid=%s"
                    + "&secret=%s"
                    + "&code=%s"
                    + "&grant_type=authorization_code";
            //拼接三个参数   id  密钥  code值
            String accessTokenUrl = String.format(
                    baseAccessTokenUrl,
                    WxPropertiesUtils.WX_OPEN_APP_ID,
                    WxPropertiesUtils.WX_OPEN_APP_SECRET,
                    code);
            //根据临时票据请求微信固定地址，得到access_token 和 openid
            String accessTokenInfo = HttpClientUtil.get(accessTokenUrl);

            //从accessTokenInfo中去除access_token 和 openid，转换成map集合，再通过key取值
            Gson gson = new Gson();
            HashMap mapAccessTokenInfo = gson.fromJson(accessTokenInfo, HashMap.class);
            String accessToken = (String) mapAccessTokenInfo.get("access_token");
            String openid = (String) mapAccessTokenInfo.get("openid");

            //把扫码人信息加入到数据库中
            UcenterMember member = memberService.getOpenIdMember(openid);
            if(member == null) { //判断数据库表中是否存在相同的用户信息，根据openId判断
                //根据 access_token 和 openid 请求微信资源服务器，获取扫描人信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                //拼接参数
                String userInfoUrl = String.format(
                        baseUserInfoUrl,
                        accessToken,
                        openid);
                String userInfo = HttpClientUtil.get(userInfoUrl);
                //获取userInfo扫描人的信息
                HashMap mapUserInfo = gson.fromJson(userInfo, HashMap.class);
                String nickName = (String) mapUserInfo.get("nickname");
                String headImgUrl = (String) mapUserInfo.get("headimgurl");

                member = new UcenterMember();
                member.setOpenid(openid);
                member.setNickname(nickName);
                member.setAvatar(headImgUrl);
                memberService.save(member);
            }

            //登录,使用jwt生成token字符串
            String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());

            //返回首页面,因为端口号不同存在跨域问题，cookie不能跨域，所以这里使用url重写
            return "redirect:http://localhost:3000?token=" + jwtToken;
        } catch (Exception e) {
            throw new LongMaoException(20001, "登录失败");
        }
    }
}
